#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from tack.lib import string_app, content_headers, status_codes
from tack.lib.jsontools import json_dumps

display_format = '%d %b %Y'
week_display_format = '%A'
ymd_format = '%Y-%m-%d'

def today(environ, start_response):
    seed_day = date.today()
    output = build_5day_info(seed_day)
    output = json_dumps(output, indent=2)
    return string_app(output)(environ, start_response)


def anyday(environ, start_response):
    disgroups = environ['dispatcher.groups']
    try:
        date_list = disgroups['date'].split('-')
        seed_day = date(int(date_list[0]), int(date_list[1]), int(date_list[2]))
    except:
        start_response(status_codes.error, content_headers.default_plain())
        return ['Error']
    output = build_5day_info(seed_day)
    output = json_dumps(output, indent=2)
    return string_app(output)(environ, start_response)
    
def build_5day_info(seed_day):
    output = {}
    if seed_day.weekday() == 6:
        day_offset = 1
    else:
        day_offset = 0 - seed_day.weekday()
    first_day = seed_day + timedelta(days=day_offset)
    day_list = []
    for offset in [0,1,2,3,4]:
        info = {}
        throwaway = first_day + timedelta(days=offset)
        info['date'] = throwaway.strftime(ymd_format)
        info['display'] = throwaway.strftime(display_format).upper()
        info['dow'] = throwaway.strftime("%A")
        day_list.append(info) 
    output['days'] = day_list
    output['today'] = date.today().strftime(ymd_format)
    output['display'] = date.today().strftime(display_format).upper()
    output['previous'] = (first_day + timedelta(days=-8)).strftime(ymd_format)
    output['next'] = (first_day + timedelta(days=6)).strftime(ymd_format)
    return output
    
